package Windows.Search;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;

import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableColumn;

import Client.ClientListener;
import Client.MsgEvent;
import Tools.IMG;
import Tools.JLabelStyle;
import Tools.Log;
import Windows.MainWindows;
import Windows.ResToolBar;
import Windows.DownLoads.NewDownloadFrame;
import Windows.DownLoads.ShowDownloadPanel;
import Windows.Tree.PanelTreeNodeInterface;
import Windows.Tree.TreeNodePic;
import WindowsModule.Talking;
import WindowsModule.Update;
import XML.XML;
import XML.XMLNode;

public class ResSearchTable extends JScrollPane implements ClientListener, MouseListener, MouseMotionListener, PanelTreeNodeInterface {
	JTable table = new JTable();
	SearchTableModel mt;
	Date readyTime;
	JPopupMenu jpm = new JPopupMenu();
	ShowDownloadPanel sdp;
	ResToolBar rtb;
	public final NewDownloadFrame ndf;// 新建任务窗口
	JMenuItem jmD = new JMenuItem("立即下载");
	JMenuItem jmuser = new JMenuItem("用户资料");
	JMenuItem jmhy = new JMenuItem("扩展/收缩");
	JMenuItem jmpl = new JMenuItem("资源评论");
	JMenuItem jmbg = new JMenuItem("资源信息");
	public final JMenuItem jmcls = new JMenuItem("关闭搜索");
	final TreeNodePic treeNode;
	private SeachTabbedPane stp;
	Date startTime;

	private static Date time;

	private static XMLNode xn;

	public static void main(String args[]) {

		// ResSearchTable rst = new ResSearchTable();
		// JFrame f = new JFrame();
		// f.getContentPane().add(rst, BorderLayout.CENTER);
		// f.setTitle("TableEventHandle");
		// f.pack();
		// f.setVisible(true);
		// StringBuffer sb = new StringBuffer("2M/s");
		// Object[] objs = { "安全", "资源名称", "类型", "评论", "文件大小", "更新日期", sb,
		// "贡献者",
		// "MD5" };
		// rst.mt.addRow(objs);
		// sb.append("!");
		// f.addWindowListener(new WindowAdapter() {
		// public void windowClosing(WindowEvent e) {
		// System.exit(0);
		// }
		// });
	}

	public ResSearchTable(XMLNode xf, ShowDownloadPanel sdp, SeachTabbedPane stp, ResToolBar rtb) {
		this.sdp = sdp;
		this.rtb = rtb;
		this.stp = stp;
		startTime = new Date();// 超时计时开始
		mt = new SearchTableModel(table);

		setViewportView(table);
		table.setBackground(Color.BLUE);
		table.setForeground(Color.black);
		this.setForeground(Color.BLUE);
		this.setBackground(Color.BLUE);
		table.getColumn("安全").setMaxWidth(30);// 修改列宽
		table.getColumn("类型").setMaxWidth(60);// 修改列宽
		table.getColumn("评论").setMaxWidth(50);// 修改列宽
		table.getColumn("资源大小").setMaxWidth(60);// 修改列宽
		table.getColumn("更新日期").setMaxWidth(180);// 修改列宽
		table.getColumn("速度").setMaxWidth(100);// 修改列宽
		// table.getColumn("速度").setResizable(false);
		table.getColumn("速度").setPreferredWidth(100);
		table.getColumn("分享者").setMaxWidth(160);// 修改列宽
		table.getColumn("资源数").setMaxWidth(60);// 修改列宽
		table.getColumn("MD5").setMaxWidth(180);// 修改列宽
		// TableColumn tc = table.getColumn("速度");
		table.setPreferredScrollableViewportSize(new Dimension(550, 30));
		readyTime = new Date();
		Tools.TableStyle.setDefaultStyle(table);
		table.setBackground(Color.WHITE);
		init();
		ndf = new NewDownloadFrame(sdp);

		treeNode = new TreeNodePic(xf.get("keys"), IMG.SearNode);
		seach(xf);// 发送搜索指令

		Timer t = new Timer();
		t.schedule(new TimerTask() {

			@Override
			public void run() {
				if (mt.getRowCount() <= 0) {
					XMLNode xn = new XMLNode(null, "FILE");
					xn.put("safety", "1");
					xn.put("name", "对不起，搜索任务超时。");
					xn.put("userid", "");
					xn.put("md5", "");
					xn.put("size", "-1");
					xn.put("time", "-1");
					xn.put("pip", "");
					xn.put("address", "");
					xn.put("speed", "3000");
					mt.addRow(xn);
				}

			}

		}, 30000);// 30秒超时

	}

	/**
	 * 下载选中
	 */
	public void Download() {
		XMLNode xf = getSelectXml();
		if (xf != null)
			ndf.setNewTask(xf, false);

	}

	public int getSelectRow() {
		return table.getSelectedRow();
	}

	/**
	 * 取当前选中行的指定列的对象
	 * 
	 * @param column
	 * @return
	 */
	public Object getSelectValue(int column) {
		int i = table.getSelectedRow();
		if (i == -1)
			return "";
		else
			return table.getValueAt(i, column);
	}

	public XMLNode getSelectXml() {
		int i = table.getSelectedRow();
		if (i == -1)
			return null;
		return mt.getXmlFlag(i);
	}

	@Override
	public TreeNodePic getTreeNode() {

		return treeNode;
	}

	public void init() {

		jpm.add(jmD);
		jpm.add(jmuser);
		jpm.add(jmhy);
		jpm.add(jmpl);
		jpm.add(jmbg);
		jpm.add(jmcls);

		table.addMouseListener(this);
		table.addMouseMotionListener(this);
		jmD.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {

				Download();
			}

		});
		jmuser.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				XMLNode xn = getSelectXml();
				String UserID = xn.get("userid");
				if (UserID != null && !UserID.equals("*")) {
					new Update().initInfo(UserID, false);
				}
			}
		});
		jmhy.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				mt.Expand(getSelectXml());
			}
		});
		jmpl.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				XMLNode xn = getSelectXml();
				if (xn != null) {
					String userid = xn.get("userid");
					new Talking(userid);
				}
			}
		});
		jmbg.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				XMLNode xn = getSelectXml();
				if (xn != null) {
					MainWindows.getResInfo().display(xn);
				}
			}
		});
	}

	@Override
	public void mouseClicked(MouseEvent e) {

	}

	@Override
	public void mouseDragged(MouseEvent arg0) {

	}

	@Override
	public void mouseEntered(MouseEvent e) {

	}
	@Override
	public void mouseExited(MouseEvent e) {

	}

	@Override
	public void mouseMoved(MouseEvent e) {

		TableColumn tc = table.getColumn("安全");

		// ---取鼠标行（待续）

		if (tc != null && e.getX() <= tc.getWidth()) {
			table.setCursor(JLabelStyle.handCur);
		} else {
			if (table.getCursor().getType() != JLabelStyle.defCur.getType())
				table.setCursor(JLabelStyle.defCur);
		}
	}

	@Override
	public void mousePressed(MouseEvent e) {

	}

	@Override
	public void mouseReleased(MouseEvent e) {
		if (e.getButton() == 1 && this.getSelectRow() != -1) {
			TableColumn tc = table.getColumn("安全");
			if (tc != null && e.getX() <= tc.getWidth()) {
				mt.Expand(getSelectXml());
				return;
			}
			if (time == null) {
				time = new Date();
				xn = getSelectXml();
				return;
			}
			Date endTime = new Date();
			long t = endTime.getTime() - time.getTime();// 点击间隔
			if (t < 400 && xn == getSelectXml()) {
				int pip = 0;
				try {
					pip = Integer.parseInt(xn.get("pip"));
				} catch (Exception e2) {
				}
				if (t > 190 && pip > 1) {
					mt.Expand(xn);
				} else {
					Download();
				}
				time = null;
			} else {
				time = endTime;
				xn = getSelectXml();
			}
		} else if (e.getButton() == 3 && this.getSelectRow() != -1) {// 鼠标右键单击
			jpm.show(table, table.getMousePosition().x, table.getMousePosition().y);

		}
	}

	@Override
	public void onCloseEvent(Client.CloseEvent cce) {
	}

	// --搜索结果到达
	@Override
	public void onMsgEvent(MsgEvent ce) {
		String flg = ce.getCmd().FLAG;// --取大写指令字符串
		if (flg.equalsIgnoreCase("sresult")) {// ---文件搜索结果
			XML cmd = ce.getCmd();
			int i = Integer.parseInt(cmd.get("id"));// 取搜索表格实体哈希值
			if (i == this.hashCode()) {
				String id = cmd.get("userid");// 所有者用户名
				String address = cmd.get("address");// 所有者IP地址
				String sport = cmd.get("sport");// 所有者监听端口

				Vector<XMLNode> al = new Vector<XMLNode>(0);
				cmd.getList("sresult", al, false);// 取文件列表集合
				// log.print("[addLiset]" + al.size());
				XMLNode xf;
				// 将资源的用户信息添加到属性
				for (i = 0; i < al.size(); i++) {
					xf = al.get(i);
					if (xf.FLAG.toUpperCase().equals("FILE")) {
						xf.put("userid", id);
						xf.put("address", address);
						xf.put("sport", sport);
						xf.put("speed", String.valueOf(new Date().getTime() - readyTime.getTime()));
					} else
						al.remove(i--);// 删除当前，并回缩
				}
				mt.addRowList(al);
			}
		}
	}

	/**
	 * 搜索文件,向服务器发送消息
	 * 
	 * @param keys
	 * @param minSize
	 * @param maxSize
	 * @param tab
	 *            返回文件列表的表格
	 */
	public void seach(XMLNode s) {
		s.put("id", String.valueOf(this.hashCode()));// 表格的哈希码
		MainWindows.getInstance().client.send(s);
		Log.print("[Client][send]Seach ->" + s);
	}
}
